package com.zhi.syc.data_applist.services;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.exifinterface.media.ExifInterface;

import com.google.gson.Gson;
import com.zhi.syc.data_applist.beans.ASImageInfoBean;
import com.zhi.syc.data_applist.logger.ASLogger;
import com.zhi.syc.data_applist.util.ASUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ASImageInfo {

    public static ArrayList<ASImageInfoBean> getImageList(Context context) {
        ArrayList<ASImageInfoBean> arrayList = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
            if (cursor == null) {
                return arrayList;
            }

            while (cursor.moveToNext()) {

                ASImageInfoBean imageInfoBean = new ASImageInfoBean();
                String filePath = cursor.getString(cursor.getColumnIndex("_data"));
                Uri filePathUri = null;
                ExifInterface exifInterface = null;
                InputStream imgInputStream = null;

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    String id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
                    filePathUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(id).build();
                    filePathUri = MediaStore.setRequireOriginal(filePathUri);
                    imgInputStream = context.getContentResolver().openInputStream(filePathUri);
                    exifInterface = new ExifInterface(imgInputStream);
                } else {
                    exifInterface = new ExifInterface(filePath);
                }

                ASLogger.d("ASImageInfo", "checkAblum: filePath: " + filePath);

                if(exifInterface==null){
                    continue;
                }

                double[] latlong = exifInterface.getLatLong();
                ASLogger.d("ASImageInfo", "checkAblum: latlong: " + latlong);


                imageInfoBean.setName(ASUtil.getFileName(filePath));

                String Model = ASUtil.safeString((exifInterface).getAttribute("Model"));
                imageInfoBean.setModel(Model);

                String Make = ASUtil.safeString((exifInterface).getAttribute("Make"));
                imageInfoBean.setMake(Make);

                String ImageWidth = ASUtil.safeString((exifInterface).getAttribute("ImageWidth"));
                imageInfoBean.setWidth(ImageWidth);

                String ImageLength = ASUtil.safeString((exifInterface).getAttribute("ImageLength"));
                imageInfoBean.setHeight(ImageLength);

                String DateTime = ASUtil.safeString((exifInterface).getAttribute("DateTime"));
                imageInfoBean.setDate(DateTime);

                String GPSLatitude = ASUtil.safeString((exifInterface).getAttribute("GPSLatitude"));
                imageInfoBean.setLatitude(GPSLatitude);

                String GPSLatitudeRef = ASUtil.safeString((exifInterface).getAttribute("GPSLatitudeRef"));
                imageInfoBean.setLatitudeRef(GPSLatitudeRef);

                String GPSLatitudeDoule = String.valueOf(dms2Dbl(GPSLatitude));
                GPSLatitudeDoule = (GPSLatitudeRef != null && GPSLatitudeRef.contains("S")) ? "-" + GPSLatitudeDoule : GPSLatitudeDoule;
                imageInfoBean.setLatitudeG(GPSLatitudeDoule);

                String GPSLongitude = ASUtil.safeString((exifInterface).getAttribute("GPSLongitude"));
                imageInfoBean.setLongitude(GPSLongitude);

                String GPSLongitudeRef = ASUtil.safeString((exifInterface).getAttribute("GPSLongitudeRef"));
                imageInfoBean.setLongitudeRef(GPSLongitudeRef);

                String GPSLongitudeDoule = String.valueOf(dms2Dbl(GPSLongitude));
                GPSLongitudeDoule = (GPSLongitudeRef != null && GPSLongitudeRef.contains("W")) ? "-" + GPSLongitudeDoule : GPSLongitudeDoule;
                imageInfoBean.setLongitudeG(GPSLongitudeDoule);

                arrayList.add(imageInfoBean);

                exifInterface = null;

                if(imgInputStream!=null) {
                    imgInputStream.close();
                    imgInputStream = null;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ((cursor != null) && (!cursor.isClosed())) {
                cursor.close();
                cursor = null;
            }
        }

        return arrayList;
    }

    public static double dms2Dbl(String sDMS) {
        if (TextUtils.isEmpty(sDMS)) {
            return 0D;
        }
        double dRV = 999.0;
        try {
            String[] DMSs = sDMS.split(",", 3);
            String s[] = DMSs[0].split("/", 2);
            dRV = (Double.parseDouble(s[0]) / Double.parseDouble(s[1]));
            s = DMSs[1].split("/", 2);
            dRV += ((Double.parseDouble(s[0]) / Double.parseDouble(s[1])) / 60);
            s = DMSs[2].split("/", 2);
            dRV += ((Double.parseDouble(s[0]) / Double.parseDouble(s[1])) / 3600);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return dRV;
    }

    public static String getRealPathFromURI(Context context, Uri contentURI) {
        String result;
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(contentURI, null, null, null, null);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (cursor == null) {
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    public static String getListZipString(Context paramContext) {
        String zipString = "";
        try {
            List<ASImageInfoBean> imageInfoBeans = getImageList(paramContext);
            String result = new Gson().toJson(imageInfoBeans).trim();
            ASLogger.d(ASImageInfo.class.getSimpleName(), "result: "+result);
            zipString = ASUtil.stringToGZIP(result);
            imageInfoBeans.clear();
            imageInfoBeans = null;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return zipString;
    }
}
